#!/usr/bin/python

import unittest
import StringIO

import Pyong
import Postie

class TestUrlParser(unittest.TestCase):
	
	def setUp(self):
		unittest.TestCase.setUp(self)
		self.url_parser = Pyong.UrlParser()

	def testShouldReturnEmptyDictionaryIfNoParamsSpecified(self):
		self.assertEqual(0, len(self.parse_url("/index.html")))

	def testShouldParseSingleParameter(self):
		self.assertEqual("bar", self.parse_url("/index.html?foo=bar")["foo"])

	def testShouldParseMultipleParameters(self):
		params = self.parse_url("/index.html?foo=bar&one=two&three=four")
		self.assertEqual("bar", params["foo"])
		self.assertEqual("two", params["one"])
		self.assertEqual("four", params["three"])

	def testShouldParseParameterNameWithNoValue(self):
		params = self.parse_url("/index.html?foo")
		self.assertEqual("", params["foo"])

	def testShouldExtractResourceFromPath(self):
		self.assertEqual("index.html", self.url_parser.get_resource("/index.html?foo=bar"))
		self.assertEqual("subdir/index.html", self.url_parser.get_resource("/subdir/index.html?foo=bar"))
		self.assertEqual("someresource", self.url_parser.get_resource("/someresource"))

	def parse_url(self, url):
		return self.url_parser.get_params(url)

class TestGetTipsRequestProcessor(unittest.TestCase):
	
	def testShouldSerialisePosts(self):
		request_processor = Pyong.GetTipsRequestProcessor(MockPostRepository(TEST_POSTS))
		output = StringIO.StringIO()
		expected = '[{"category": "cat1", "text": "description1", "id": 0, "title": "title1"}, {"category": "cat2", "text": "description2", "id": 1, "title": "title2"}]'
		request_processor.write_response(output)
		self.assertEqual(expected, output.getvalue())
	
	def testShouldSerialiseEmptyResponse(self):
		request_processor = Pyong.GetTipsRequestProcessor(MockPostRepository([]))
		output = StringIO.StringIO()
		expected = '[]'
		request_processor.write_response(output)
		self.assertEqual(expected, output.getvalue())

class MockPostRepository:
	def __init__(self, posts):
		self.posts = posts
		
	def load_all_posts(self):
		return self.posts
		
TEST_POSTS = [Postie.Post(0, "cat1", "title1", "description1"), 
		Postie.Post(1, "cat2", "title2", "description2")]

if __name__ == "__main__":
	unittest.main()
		
